//
//  searchController.m
//  pacc
//
//  Created by 测试 on 2018/5/21.
//  Copyright © 2018年 测试. All rights reserved.
//

#import "searchController.h"
#import "SlideBarCell.h"
#import "taskDetailsCVc.h"
#import "yuepianController.h"
@interface searchController ()<UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating,UISearchBarDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UISearchController *searchController;
// 数据源数组
@property (nonatomic, strong) NSMutableArray *datas;

// 搜索结果数组
@property (nonatomic, strong) NSMutableArray *results;

@property(nonatomic,copy)NSString * nameStr;


@end

@implementation searchController

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self loaddata];
    // 创建UISearchController, 这里使用当前控制器来展示结果
    UISearchController *search = [[UISearchController alloc]initWithSearchResultsController:nil];
    // 设置结果更新代理
    self.searchController = search;
//    search.searchBar.delegate = self;
    search.searchBar.placeholder = @"搜索";
    self.definesPresentationContext = YES;
    [_searchController.searchBar setValue:@"取消" forKey:@"_cancelButtonText"];
    search.searchResultsUpdater = self;
    // 因为在当前控制器展示结果, 所以不需要这个透明视图
    search.dimsBackgroundDuringPresentation = NO;
    // 将searchBar赋值给tableView的tableHeaderView
    self.tableView.tableHeaderView = search.searchBar;
    _datas = [NSMutableArray arrayWithObjects:@"1",@"2",nil];
    [self setupNavBar];
    // Do any additional setup after loading the view from its nib.
}

-(void)loaddata{
    NSMutableDictionary *dic =[NSMutableDictionary dictionary];
    NSString *urlstr = @"ordergetDoctorOrder";
    switch (_currentPage) {
        case 0:
            //已接单
            [dic setValue:@2 forKey:@"status"];
            _nameStr =@"已接单";
            
            break;
        case 1:
            //已接单
            [dic setValue:@3 forKey:@"status"];
            _nameStr =@"已完工";
            break;
        case 2:
            //已接单
            [dic setValue:@4 forKey:@"status"];
            _nameStr =@"已审核";
            break;
        case 3:
            //已接单
            [dic setValue:@5 forKey:@"status"];
            _nameStr =@"未通过";
            break;
        case 4:
            //已接单
            [dic setValue:@6 forKey:@"status"];
            _nameStr =@"已付款";
            break;
        case 5:
            //已接单
            //            [dic setValue:@2 forKey:@"status"];
            _nameStr =@"全部";
            break;
        case 6:
            //已接单
            //            [dic setValue:@2 forKey:@"status"];
            urlstr = @"ordergetNotAcceptOrder";
            _nameStr =@"3";
            break;
        case 7:
            //已接单
            //            [dic setValue:@2 forKey:@"status"];
            _nameStr =@"全部";
            break;
        default:
            break;
    }
    [dic setValue:@10 forKey:@"keyWord"];
    [dic setValue:@1 forKey:@"page"];
    [dic setValue:my_AppDelegate.token forKey:@"token"];
    self.tableView.scrollEnabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.tableView.scrollEnabled = YES;
    });
    [NetWorking startPOSTRequestWithUrl:urlstr parameters:dic logMes:_nameStr show:NO success:^(NSDictionary *data) {
        self.tableView.scrollEnabled = YES;
        NSArray *arr = [data objectForKey:@"data"];
        if ([arr isEqual:[NSNull null]]) {
            return ;
        }
        if (arr.count == 0||!arr) {
//            self->_myImageView.hidden = NO;
        }else{
//            self->_myImageView.hidden = YES;
            
        }
        if (arr.count==0||arr.count<10||!arr){
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }
        self->_dataSource = [woderenwuModel modelSformDics:arr];
   
        [self.tableView reloadData];

    } failure:^(NSError *error) {
        
    }];
}
- (void)setupNavBar {
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    view.backgroundColor = baseBlueColor;
    [self.view addSubview:view];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 20, 80, 44);
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [_searchController.searchBar resignFirstResponder];
    [self.view endEditing:NO];}

- (void)backBtnClick {
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height-64) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UIAccessibilityTraitNone;
        [self.view addSubview:_tableView];
    }
    
    return _tableView;
}

- (NSMutableArray *)datas {
    if (_datas == nil) {
        _datas = [NSMutableArray arrayWithCapacity:0];
    }
    
    return _datas;
}

- (NSMutableArray *)results {
    if (_results == nil) {
        _results = [NSMutableArray arrayWithCapacity:0];
    }
    
    return _results;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

// 将点击tableviewcell的时候收回 searchBar 键盘
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_searchController.searchBar resignFirstResponder];
    [self.view endEditing:NO];
    return indexPath;
}
// 滑动的时候 searchBar 回收键盘

#pragma mark --tableView--
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
//    // 这里通过searchController的active属性来区分展示数据源是哪个
//    if (self.searchController.active) {
//
//        return self.results.count ;
//    }
//
//    return self.datas.count;
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BOOL nibsRegistered=NO;
    if (!nibsRegistered) {
        UINib *nib=[UINib nibWithNibName:@"SlideBarCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:@"SlideBarCell"];
        nibsRegistered=YES;
    }
    
    
    SlideBarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SlideBarCell"];
   
    cell.arrData = _dataSource[indexPath.row];
    [cell.yuepianBtn setTitle:cell.zid forState:UIControlStateHighlighted];
    [cell.yuepianBtn addTarget:self action:@selector(yuepian:) forControlEvents:UIControlEventTouchUpInside];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //    NSLog(@"%@",cell.tipTitle.text);
    return cell;
    
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
//    if (cell == nil) {
//        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellID"];
//    }
//
//    // 这里通过searchController的active属性来区分展示数据源是哪个
//    if (self.searchController.active ) {
//
//        cell.textLabel.text = [self.results objectAtIndex:indexPath.row];
//    } else {
//
//        cell.textLabel.text = [self.datas objectAtIndex:indexPath.row];
//    }
//
//    return cell;
}
-(void)yuepian:(UIButton*)sender{
    yuepianController *vc = [yuepianController new];
    NSString * zid = [sender titleForState:UIControlStateHighlighted];
    //    vc.zid = zid;
    vc.yuepianURL = zid;
    [self.navigationController pushViewController:vc animated:YES];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.searchController.active) {
        NSLog(@"选择了搜索结果中的%@", [self.dataSource objectAtIndex:indexPath.row]);
    } else {
        
        NSLog(@"选择了列表中的%@", [self.dataSource objectAtIndex:indexPath.row]);
    }
    if (!my_AppDelegate.grabO) {
//        return;
    }
    SlideBarCell * cell =[tableView cellForRowAtIndexPath:indexPath];
    taskDetailsCVc *vc =[taskDetailsCVc new];
    vc.type = _currentPage;
    vc.zid = cell.zid;
    NSString * nameStr;
    switch ([cell.odrStatus intValue]) {
        case 1:
            nameStr = @"已下单";
            break;
        case 2:
            nameStr = @"已接单";
            
            break;
        case 3:
            nameStr = @"已完工";
            
            break;
        case 4:
            nameStr = @"已审核";
            
            break;
        case 5:
            nameStr = @"未通过";
            
            break;
        case 6:
            nameStr = @"已付款";
            break;
            
        default:
            break;
    }
    vc.odrStatus = nameStr;
    vc.returnValueBlock = ^(BOOL passedValue){
        
//        self.isFrash = passedValue;
        
    };
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    NSString *inputStr = searchController.searchBar.text ;
    if ([inputStr isEqualToString:@""]) {
        return;
    }
    
    NSMutableDictionary *dic =[NSMutableDictionary dictionary];
    NSString *urlstr = @"ordergetDoctorOrder";
    switch (_currentPage) {
        case 0:
            //已接单
            [dic setValue:@2 forKey:@"status"];
            _nameStr =@"已接单";
            
            break;
        case 1:
            //已接单
            [dic setValue:@3 forKey:@"status"];
            _nameStr =@"已完工";
            break;
        case 2:
            //已接单
            [dic setValue:@4 forKey:@"status"];
            _nameStr =@"已审核";
            break;
        case 3:
            //已接单
            [dic setValue:@5 forKey:@"status"];
            _nameStr =@"未通过";
            break;
        case 4:
            //已接单
            [dic setValue:@6 forKey:@"status"];
            _nameStr =@"已付款";
            break;
        case 5:
            //已接单
            //            [dic setValue:@2 forKey:@"status"];
            _nameStr =@"全部";
            break;
        case 6:
            //已接单
            //            [dic setValue:@2 forKey:@"status"];
            urlstr = @"ordergetNotAcceptOrder";
            _nameStr =@"搜索平台任务";
            break;
        case 7:
            //已接单
            //            [dic setValue:@2 forKey:@"status"];
            _nameStr =@"全部";
            break;
        default:
            break;
    }
    [dic setValue:inputStr forKey:@"keyWord"];
    [dic setValue:@1 forKey:@"page"];
    [dic setValue:_sum forKey:@"size"];
    [dic setValue:my_AppDelegate.token forKey:@"token"];
    self.tableView.scrollEnabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.tableView.scrollEnabled = YES;
    });
    [NetWorking startPOSTRequestWithUrl:urlstr parameters:dic logMes:_nameStr show:NO success:^(NSDictionary *data) {
        self.tableView.scrollEnabled = YES;
        NSArray *arr = [data objectForKey:@"data"];
        if ([arr isEqual:[NSNull null]]) {
            return ;
        }
        if (arr.count == 0||!arr) {
            //            self->_myImageView.hidden = NO;
        }else{
            //            self->_myImageView.hidden = YES;
            
        }
        if (arr.count==0||arr.count<10||!arr){
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }
        self->_dataSource = [woderenwuModel modelSformDics:arr];
        
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        
    }];
    
    if (self.results.count > 0) {
        [self.results removeAllObjects];
    }
    for (NSString *str in self.datas) {
        
        if ([str.lowercaseString rangeOfString:inputStr.lowercaseString].location != NSNotFound) {
            
            [self.results addObject:str];
        }
    }
    
    [self.tableView reloadData];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"搜索");
}
// 视图显示的时候, 隐藏系统导航  使用自定义导航
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (self.navigationController) {
        
        self.navigationController.navigationBarHidden = YES;
    }
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    searchBar.showsCancelButton = YES;
    for (id cencelButton in [searchBar.subviews[0] subviews])
    {
        if([cencelButton isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)cencelButton;
//            [btn setTitle:@"取消"  forState:UIControlStateNormal];
        }
    }
}
// 视图消失的时候, 将系统导航恢复
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    if (self.navigationController) {
        self.navigationController.navigationBarHidden = NO;
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
